﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint.Taxonomy;

namespace MS.InformationManagement.BLL.ChildRadicados
{
    public class ChildRadicados
    {

        Dictionary<string, string> formUrl;

        public ChildRadicados()
        {
            formUrl = new Dictionary<string, string>();
            formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_ENTRADA] = "InsertarRadicado.aspx";
            formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA] = "InsertarRadicadoSalida.aspx";
            formUrl[GlobalConstants.METADATA_TERM_TIPO_INTERNO] = "InsertarRadicadoInterno.aspx";
        }

        public List<Radicado> GetChildRadicados(List<string> childs, string list)
        {
            SPQuery query = new SPQuery();
            query.Query = getInFilters(childs);
            query.ViewAttributes = "Scope='RecursiveAll'";
            //query.ViewFields = string.Format("<FieldRef Name='{0}'/><FieldRef Name='{1}'/><FieldRef Name='{2}'/>",CustomSiteColumns.FIELD_DOCUMENT_RADICADO,CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT,CustomSiteColumns.FIELD_DOCSET_KIND);
            SPListItemCollection radicados = SPContext.Current.Web.Lists[new Guid(list)].GetItems(query);
            return (from radicado in radicados.OfType<SPListItem>()
                    select new Radicado()
                    {
                      NoRadicado = radicado[CustomSiteColumns.FIELD_DOCUMENT_RADICADO].ToString(),
                      Created = (DateTime)radicado[SPBuiltInFieldId.Created],
                      RemitenteDestinatario = radicado[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString(),
                      TipoDocumento = ((TaxonomyFieldValue)radicado[CustomSiteColumns.FIELD_DOCSET_KIND]).Label,
                      Path = string.Format("/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicadoSalida.aspx?strategy=view&List=" + list + "&ID=" + radicado.ID, formUrl[((TaxonomyFieldValue)radicado[CustomSiteColumns.FIELD_DOCSET_KIND]).Label])
                    }).ToList();
        }

        private string getInFilters(List<string> childs)
        { 
            StringBuilder sb = new StringBuilder()
            .Append("<Where>")
            .Append("<In>")
            .Append(string.Format("<FieldRef Name='{0}' />", CustomSiteColumns.FIELD_DOCUMENT_RADICADO))
            .Append("<Values>");
            foreach(var child in childs)
            {
                sb.Append(string.Format("<Value Type='Text'>{0}</Value>",child));
            }
            sb.Append("</Values>")
            .Append("</In>")
            .Append("</Where>");
            return sb.ToString();
        }

    }
}
